package com.ship.edge.utils;

import com.alibaba.fastjson.JSONObject;
import com.ship.edge.config.MqttConfig;
import com.ship.edge.outfile.OutputKsbgCsvFile;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class MqttCustomCallback implements org.eclipse.paho.client.mqttv3.MqttCallback {

    @Resource
    private MqttConfig mqttConfig;

    @Resource
    private OutputKsbgCsvFile outputKsbgCsvFile;

    private static MqttClient client;

    private static String _topic;
    private static String _qos;
    private static String _msg;

    @Override
    public void connectionLost(Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
        if (client == null || !client.isConnected()) {
            while(true) {
                try {
                    log.info("[MQTT] 监测到连接断开，30S之后尝试重连...");
                    Thread.sleep(30000);
                    MqttCustomClient customClient = mqttConfig.getMqttPushClient();
                    client = MqttCustomClient.getClient();
                    if (client == null || !client.isConnected()) {
                        continue;
                    }else{
                        break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }

        }

    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        // subscribe后得到的消息会执行到这里面
        log.info("接收消息主题 : " + topic);
        log.info("接收消息Qos : " + mqttMessage.getQos());
        log.info("接收消息内容 : " + new String(mqttMessage.getPayload()));

        _topic = topic;
        _qos = mqttMessage.getQos()+"";
        _msg = new String(mqttMessage.getPayload());
        if(topic.toLowerCase().contains("ksbg")){
            outputKsbgCsvFile.mqttMsgToBean(topic, new String(mqttMessage.getPayload()));
        }


    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.info("deliveryComplete---------" + iMqttDeliveryToken.isComplete());
    }

    //别的Controller层会调用这个方法来  获取  接收到的硬件数据
    public String receive() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("topic", _topic);
        jsonObject.put("qos", _qos);
        jsonObject.put("msg", _msg);
        return jsonObject.toString();
    }

}
